/* 
 * File:   main.c
 * Author: xata
 *
 * Created on 9 Август 2012 г., 22:05
 */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <pthread.h>
volatile short int iteration = 0;
volatile int com_fdesc;
volatile short int pot_number=1;
volatile unsigned short int pot_val[] = {0,0};
volatile unsigned short int jack_status=0;

void parser(int signl);
void* X_ui(void* args);
void* start_jack(void* args);

int main(int argc, char** argv) {
    com_fdesc = open("/dev/ttyS0", O_RDONLY | O_NOCTTY | O_NONBLOCK);
    if (com_fdesc<0) {printf("ERROR OPENING TTY"); exit(-1);}
    struct termios oldcom, com;
    struct sigaction signal;
    pthread_t gui_thread;
    pthread_create(&gui_thread, NULL, X_ui, NULL);
    pthread_t jack_thread;
    pthread_create(&jack_thread, NULL, start_jack, NULL);
//    start_jack(NULL);
    bzero(&signal, sizeof(signal));
    fcntl(com_fdesc, F_SETOWN, getpid());
    fcntl(com_fdesc, F_SETFL, FASYNC);
    tcgetattr(com_fdesc, &oldcom);
    bzero(&com, sizeof(com));
    com.c_cflag = B57600|CS8|CSTOPB|CREAD|PARODD;
    com.c_iflag = IGNPAR;
    tcsetattr(com_fdesc,TCSANOW,&com);
    signal.sa_handler = parser;
    sigaction(SIGIO,&signal,NULL);
    while (1){
        if(getchar()=='q'||jack_status==1){
            exit(0);
        }
    };
}

void parser(int signl){
    unsigned char *buf = malloc(sizeof(unsigned char));
    read(com_fdesc,buf,1);
    switch (*buf){
        case '\n': 
            if (iteration==0){
                (iteration)++;
            }
            break;
        case 'p':
            if (iteration==1){
                (iteration)++;
            }else if (iteration!=0||iteration!=2){
                pot_val[pot_number-1]=(unsigned int)(*buf);
            }
            break;
        case'a':
            if(iteration==2){
                (iteration)++;
                pot_number=1;
            }else if (iteration!=0||iteration!=1){
                pot_val[pot_number-1]=(unsigned int)(*buf);
            }
            break;
        case'b':
            if(iteration==2){
                (iteration)++;
                pot_number=2;
            }else if (iteration!=0||iteration!=1){
                pot_val[pot_number-1]=(unsigned int)(*buf);
            }
            break;
        default:
            if(iteration==3){
                pot_val[pot_number-1]=(unsigned int)(*buf);
                (iteration)=0;
            }
            break;
            
    }
    free(buf);
    
}
